<?php
// +----------------------------------------------------------------------
// | Description: 合同
// +----------------------------------------------------------------------
// | Author:  Michael_xu | gengxiaoxu@5kcrm.com
// +----------------------------------------------------------------------
namespace app\crm\model;

use app\admin\model\Record;
use app\admin\model\User;
use think\Db;
use app\admin\model\Common;
use think\Request;
use think\Validate;

class Accounting extends Common
{
    protected $name = 'crm_accounting';
    protected $createTime = 'createtime';
    protected $updateTime = '';
    protected $autoWriteTimestamp = true;
    /**
     * [getDataList 合同list]
     * @author Michael_xu
     * @param     [string]                   $map [查询条件]
     * @param     [number]                   $page     [当前页数]
     * @param     [number]                   $limit    [每页数量]
     * @return    [array]                    [description]
     */
    public function getDataList($request)
    {
        $user_id = $request['user_id'];

        $where=["contract_id"=>$request["contract_id"]];

        //列表展示字段
        // $indexField = $fieldModel->getIndexField('crm_contract', $user_id);

        $order = ['accounting.createtime desc'];
        $list = db('crm_accounting')
            ->alias('accounting')
            //->join('__CRM_CONTRACT__ contract','contract.contacts_id = accounting.contacts_id','LEFT')
            ->join('__ADMIN_USER__ accountancy_user','accounting.accountancy_user_id = accountancy_user.id','LEFT')//做账会计
            ->join('__ADMIN_USER__ admin','accounting.admin_id = admin.id','LEFT')//审核人
            ->where($where)
            ->limit(($request['page']-1)*$request['limit'], $request['limit'])
            ->field("accounting.*,accountancy_user.realname as 'accountancy_user_realname',admin.realname as admin_realname,
            from_unixtime(createtime, '%Y-%m-%d %H:%i:%s') createtime,from_unixtime(examine_time, '%Y-%m-%d %H:%i:%s') examine_time")
            ->order($order)
            ->select();
        $dataCount = db('crm_accounting')
            ->alias('accounting')
            ->where($where)
            ->count('accounting.contract_id');

        //新增 统计合同金额和回款金额 end
        $data = [];
        $data['list'] = $list;
        $data['dataCount'] = $dataCount ? : 0;
        /*$data['data']['sumMoney'] = $sumMoney ? : 0.00;
        $data['data']['unReceivablesMoney'] = $unReceivablesMoney ? : 0.00;*/
        return $data;
    }
    /**
     * 计算月代理费单价
     * */
    public function monthlyAgencyPrice($contract=[],$contract_all="")
    {
        /*$price=0;
        //(回款-成本（核定【销售自己填写】）-退款-工本费)/服务期数
        if(empty($contract)){
            //统计所有
            $unMoney=Receivables::whereIn("contract_id",$contract_all["contract_ids"])->where(['check_status' => 2])->sum('money');
            $ids=explode(",",$contract_all["cost_production"]);
            $contract_ids='';
            foreach ($ids as $k=>$v){
                if($k==0){
                    $contract_ids=$v;
                }else{
                    $contract_ids.="|".$v;
                }
            }
            if($unMoney>0){
                $ids=db('oa_examine_relation')
                    ->where("contract_ids regexp '(^|,)(".$contract_ids."),(,|$)'")
                    //->where(['contract_ids' => ['like', '%,'.$contract['contract_id'].',%']])
                    ->column('examine_id');
                $where_examine['examine_id'] = ['in',$ids];
                $where_examine['check_status'] = ['in',[0,1,2]];
                $where_examine['category_id'] = 12;
                $money_arr=db('oa_examine')->where($where_examine)->column('money');
                $money=array_sum($money_arr);
                $price=bcsub($unMoney,$contract_all["crm_oeseng"]);//回款-成本（核定【销售自己填写】）
                $money=bcadd($money,$contract_all["cost_production"]);//退款+工本费
                $price=bcsub($price,$money,2);//-(退款+工本费)
                $price=bcdiv($price,$contract_all["crm_grvgkz"],2);///服务期数
            }
        }else{
            if($contract["unMoney"]>0){
                //已回款金额>0
                $ids=db('oa_examine_relation')->where(['contract_ids' => ['like', '%,'.$contract['contract_id'].',%']])
                    ->column('examine_id');
                $where_examine['examine_id'] = ['in',$ids];
                $where_examine['check_status'] = ['in',[0,1,2]];
                $where_examine['category_id'] = 12;
                $money_arr=db('oa_examine')->where($where_examine)->column('money');
                $money=array_sum($money_arr);
                $price=bcsub($contract["unMoney"],$contract["crm_oeseng"]);//回款-成本（核定【销售自己填写】）
                $money=bcadd($money,$contract["cost_production"]);//退款+工本费
                $price=bcsub($price,$money,2);//-(退款+工本费)
                $price=bcdiv($price,$contract["crm_grvgkz"],2);
            }
        }*/
        //(回款-成本（核定【销售自己填写】）-退款-工本费)/服务期数
       /* $price=0;
        $unMoney = Receivables::where(['contract_id' => $contract["contract_id"],'check_status' => 2])->sum('money');
        if($unMoney>0){
            //已回款金额>0
            $ids=db('oa_examine_relation')->where(['contract_ids' => ['like', '%,'.$contract['contract_id'].',%']])
                ->column('examine_id');
            $where_examine['examine_id'] = ['in',$ids];
            $where_examine['check_status'] = ['in',[0,1,2]];
            $where_examine['category_id'] = 12;
            $money_arr=db('oa_examine')->where($where_examine)->column('money');
            $money=array_sum($money_arr);
            $price=bcsub($unMoney,$contract["crm_oeseng"]);//回款-成本（核定【销售自己填写】）
            $money=bcadd($money,$contract["cost_production"]);//退款+工本费
            $price=bcsub($price,$money,2);//-(退款+工本费)
            $price=bcdiv($price,$contract["crm_grvgkz"],2);
        }
        return $price;*/
       //2024-1-25 修改 查找回款金额的核定成本 start
        $crm_oeseng=Receivables::where(["contract_id"=>$contract["contract_id"],"check_status"=>2,"crm_lasahm"=>"正常核算"])->sum("crm_oeseng");
       //2024-1-25 修改 查找回款金额的核定成本 end
       //修改为 订单总金额-成本（核定【销售自己填写】）/服务期数
        $price=bcsub($contract["money"],$crm_oeseng,2);//订单总金额-成本（核定【销售自己填写】）
        $price=bcsub($price,$contract["cost_production"],2);//-(工本费)
        $price=bcdiv($price,$contract["crm_grvgkz"],2);
        return $price;
    }

    /**
     * 获取成本
     * */
    public function getCost($contract)
    {
        $ids=db('oa_examine_relation')->where(['contract_ids' => ['like', '%,'.$contract['contract_id'].',%']])
            ->where(["category_id"=>12])
            ->column('examine_id');
        $where_examine['examine_id'] = ['in',$ids];
        $where_examine['check_status'] = ['in',[0,1,2]];
        $where_examine['category_id'] = 12;
        $money_arr=db('oa_examine')->where($where_examine)->column('money');
        $money=array_sum($money_arr);
        return $money;
    }
}